<template>
  <el-row class="rowNavStyle">
    <el-col :span="24" class="colNavStyle">
      <menuButton
        ref="ref1"
        @addRoleKey="addClick"
        @closeRoleKey="batchCloseClick"
        @enableRoleKey="batchEnableClick"
        helper-path="pages/75db42"
      ></menuButton>
      <!-- <el-button type="primary" @click="open = true">Begin Tour</el-button> -->
      <!-- <div
        style="margin-left: auto; margin-right: 10px; display: flex; color: red"
      >
        <el-icon style="color: #67c23a; font-size: 22px"
          ><ChatLineRound /></el-icon
        ><span class="blink-text">下次更新:数据按钮操作权限</span>
      </div> -->
    </el-col>
  </el-row>
  <el-table
    :data="tableData"
    stripe
    :border="true"
    row-key="roleId"
    @selection-change="SelectionChange"
    :tree-props="treeProps"
    default-expand-all
    v-loading="loading"
  >
    <el-table-column type="selection" width="55" />
    <!-- 动态列 -->
    <el-table-column
      show-overflow-tooltip
      v-for="itme in columns"
      :key="itme.fieldEnName"
      :prop="itme.fieldEnName"
      :label="itme.fieldCnName"
      :min-width="itme.fieldWidth"
      :sortable="itme.fieldSortable"
      :align="itme.fieldAlign"
    >
      <template v-if="itme.fieldSlot === 'isOpen'" #default="isOpen">
        <el-switch
          :before-change="switchClick"
          v-model="isOpen.row.isOpen"
          class="ml-2"
          inline-prompt
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          active-text="开启中"
          inactive-text="关闭中"
        />
      </template>
    </el-table-column>
    <!-- <el-table-column prop="roleName" label="角色名称" />
    <el-table-column
      prop="corporationName"
      label="所属公司"
      width="300"
      show-overflow-tooltip
    />
    <el-table-column
      prop="systemName"
      label="所属系统"
      width="300"
      show-overflow-tooltip
    />
    <el-table-column prop="isOpen" label="是否使用" align="center" width="100">
      <template #default="model">
        <el-switch
          :before-change="switchClick"
          v-model="model.row.isOpen"
          class="ml-2"
          inline-prompt
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          active-text="开启中"
          inactive-text="关闭中"
        />
      </template>
    </el-table-column>
    <el-table-column
      prop="userName"
      label="创建用户"
      align="center"
      width="100"
    />
    <el-table-column
      prop="createTime"
      label="创建时间"
      align="center"
      width="150"
    /> -->
    <el-table-column label="操作" width="420">
      <template #default="scope">
        <dataRowButton
          :model="scope.row"
          @setMenuAuthKey="menuRoleClick(scope.row)"
          @setMenuButtonAuthKey="buttonRoleClick(scope.row)"
          @bindUserKey="bindUserClick(scope.row)"
          @editRoleKey="handleEdit(scope.row)"
        ></dataRowButton>
      </template>
    </el-table-column>
  </el-table>
  <!-- <el-tour v-model="open">
    <el-tour-step :target="ref1?.$el" title="如何给用户授权">
      <div>第一步:新增角色，如果角色存在，可以忽略</div>
    </el-tour-step>
    <el-tour-step
      :target="ref2?.$el"
      title="设置角色菜单权限"
      description="第二步：点击【菜单权限】按钮，设置对应角色菜单权限"
    />
    <el-tour-step
      :target="ref3?.$el"
      title="设置角色按钮权限"
      description="第三步：点击【按钮权限】按钮，设置对应角色按钮权限"
    />
    <el-tour-step
      :target="ref4?.$el"
      title="角色绑定用户"
      description="第四步：点击【绑定用户】按钮，把角色授权给用户，然后刷新浏览器查看授权"
    />
  </el-tour> -->
  <addOrEdit
    :isVisibles="isVisibles"
    :modelData="sysRole"
    :dialogTitle="dialogTitle"
    @closeBnt="colosClick"
  ></addOrEdit>
  <menuAuth
    :isVisibles="isMenuDrawerVisibles"
    :modelData="sysRole"
    :dialogTitle="menuDrawerTitle"
    @closeBnt="colosMenuDrawerClick"
  ></menuAuth>
  <buttonAuth
    :isVisibles="isButtonDrawerVisibles"
    :modelData="sysRole"
    :dialogTitle="buttonDrawerTitle"
    @closeBnt="colosButtonDrawerClick"
  ></buttonAuth>
  <bindUser
    :isVisibles="isBindUserVisibles"
    :modelData="sysRole"
    :dialogTitle="bindUserDrawerTitle"
    @closeBnt="colosBindUserDrawerClick"
  ></bindUser>
</template>
<script lang="ts" setup>
import { SysRole, SysRoleOutPut } from "@/model/role/role";
import { getAllRoleTreeList, SetRoleIsOpen } from "@/api/role";
import { onMounted, reactive, ref } from "vue";
import addOrEdit from "../role/addOrEdit.vue";
import menuAuth from "../role/menuAuth.vue";
import buttonAuth from "../role/buttonAuth.vue";
import bindUser from "../role/bindUser.vue";
import { useUserStore } from "@/store/user";
import { ButtonInstance, ElMessage, ElMessageBox } from "element-plus";
import { UpdateIsOpenInPut } from "@/model/public/public";
import menuButton from "@/components/menuButton.vue";
import dataRowButton from "@/components/dataRowButton.vue";
import { GetMenuColsByMenuId } from "@/api/publicTool";
//初始加载dom
onMounted(() => {
  GetMenuColsByMenuIdMsg();
});

//不做级联选择
const treeProps = reactive({
  checkStrictly: true,
});
//加载状态
const loading = ref(true);
//定义列
const columns = ref();
const userStore = useUserStore();
//控制弹出层显隐
const isVisibles = ref<boolean>(false);
//控制菜单权限抽屉显隐
const isMenuDrawerVisibles = ref<boolean>(false);
//控制按钮权限抽屉显隐
const isButtonDrawerVisibles = ref<boolean>(false);
//控制绑定用户抽屉显隐
const isBindUserVisibles = ref<boolean>(false);
//弹出层标题
const dialogTitle = ref<string>();
//菜单抽屉标题
const menuDrawerTitle = ref<string>();
//按钮抽屉标题
const buttonDrawerTitle = ref<string>();
//绑定用户标题
const bindUserDrawerTitle = ref<string>();
// 选中项
const selectedRows = ref<SysRoleOutPut[]>([]);

const open = ref<boolean>(true);

//角色模型数据
const sysRole = reactive<SysRole>({
  RoleId: "0",
  Pid: undefined,
  CorporationKey: "",
  SystemKey: "",
  RoleName: "",
  RoleType: 1,
  IsOpen: false,
});

//设置系统是否启用输入模型
const updateIsOpenInPut = reactive<UpdateIsOpenInPut>({
  Keys: [],
  IsOpen: false,
});

//菜单列
const GetMenuColsByMenuIdMsg = async () => {
  columns.value = await GetMenuColsByMenuId();
  if (columns.value.length > 1) {
    getAllRoleTreeMsg();
  } else {
    columns.value = [];
  }
};

//table数据
const tableData = ref<SysRoleOutPut[]>([]);
//获取table数据
const getAllRoleTreeMsg = () => {
  getAllRoleTreeList()
    .then(({ data, code }) => {
      if (code === 200) {
        tableData.value = data;
      }
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};

//复选框事件
const SelectionChange = (val: SysRoleOutPut[]) => {
  selectedRows.value = val;
};

//新增
const addClick = function () {
  const model = ref<SysRoleOutPut[]>([]);
  addOrEditMethod(model.value[0], true);
};

//编辑
const editClick = function () {
  if (selectedRows.value.length == 0) {
    ElMessage({
      message: "请选择一条数据进行编辑",
      type: "warning",
    });
  } else if (selectedRows.value.length > 1) {
    ElMessage({
      message: "只能选择一条数据进行编辑",
      type: "warning",
    });
  } else {
    addOrEditMethod(selectedRows.value[0], false);
  }
};

//行编辑事件
const handleEdit = function (model: SysRoleOutPut) {
  addOrEditMethod(model, false);
};

//新增或编辑方法
const addOrEditMethod = function (model: SysRoleOutPut, isAdd: boolean) {
  if (isAdd) {
    sysRole.RoleId = 0;
    sysRole.Pid = undefined;
    sysRole.RoleName = "";
    sysRole.CorporationKey = "";
    sysRole.SystemKey = "";
    (sysRole.RoleType = 1), (sysRole.IsOpen = true);
  } else {
    sysRole.RoleId = model.roleId;
    sysRole.Pid = model.pid == 0 ? undefined : model.pid.toString();
    sysRole.RoleName = model.roleName;
    sysRole.CorporationKey = model.corporationKey;
    sysRole.SystemKey = model.systemKey;
    (sysRole.RoleType = model.roleType), (sysRole.IsOpen = model.isOpen);
  }
  dialogTitle.value = isAdd ? "新增角色" : "编辑角色";
  isVisibles.value = true;
};

//菜单权限事件
const menuRoleClick = function (model: SysRoleOutPut) {
  if (model.corporationKey === "" || model.corporationKey === undefined) {
    ElMessage({
      message: "公司不能为空",
      type: "warning",
    });
    return;
  }
  if (model.systemKey === "" || model.systemKey === undefined) {
    ElMessage({
      message: "系统不能为空",
      type: "warning",
    });
    return;
  }

  menuDrawerTitle.value = "设置角色【" + model.roleName + "】的菜单权限";
  isMenuDrawerVisibles.value = true;
  sysRole.CorporationKey = model.corporationKey;
  sysRole.SystemKey = model.systemKey;
  sysRole.RoleId = model.roleId;
};

//按钮权限事件
const buttonRoleClick = function (model: SysRoleOutPut) {
  if (model.corporationKey === "" || model.corporationKey === undefined) {
    ElMessage({
      message: "公司不能为空",
      type: "warning",
    });
    return;
  }
  if (model.systemKey === "" || model.systemKey === undefined) {
    ElMessage({
      message: "系统不能为空",
      type: "warning",
    });
    return;
  }

  buttonDrawerTitle.value = "设置角色【" + model.roleName + "】的按钮权限";
  isButtonDrawerVisibles.value = true;
  sysRole.CorporationKey = model.corporationKey;
  sysRole.SystemKey = model.systemKey;
  sysRole.RoleId = model.roleId;
};
//绑定用户事件
const bindUserClick = function (model: SysRoleOutPut) {
  if (model.corporationKey === "" || model.corporationKey === undefined) {
    ElMessage({
      message: "公司不能为空",
      type: "warning",
    });
    return;
  }

  bindUserDrawerTitle.value = "绑定角色【" + model.roleName + "】的用户";
  isBindUserVisibles.value = true;
  sysRole.CorporationKey = model.corporationKey;
  sysRole.SystemKey = model.systemKey;
  sysRole.RoleId = model.roleId;
};

//批量关闭
const batchCloseClick = function () {
  if (selectedRows.value.length == 0) {
    ElMessage({
      message: "请选择一条数据进行操作",
      type: "warning",
    });
  } else {
    setIsOpen(false);
    updateIsOpenInPut.Keys = selectedRows.value.map((f) => f.roleId.toString());
    updateIsOpenInPut.IsOpen = false;
  }
};

//批量启用
const batchEnableClick = function () {
  if (selectedRows.value.length == 0) {
    ElMessage({
      message: "请选择一条数据进行操作",
      type: "warning",
    });
  } else {
    setIsOpen(true);
    updateIsOpenInPut.Keys = selectedRows.value.map((f) => f.roleId.toString());
    updateIsOpenInPut.IsOpen = true;
  }
};

//设置系统启用状态
const setIsOpen = function (isOpen: boolean) {
  var title = isOpen
    ? "你确认要开启选中角色，开启后角色的一切功能都将启用？"
    : "你确认要关闭选中角色，关闭后角色的一切功能都将停用！";
  ElMessageBox.confirm(title, "提示消息", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      SetRoleIsOpen(updateIsOpenInPut).then(({ data, code, msg }) => {
        if (code == 200) {
          getAllRoleTreeMsg();
          ElMessage({
            message: msg,
            type: "success",
          });
        }
      });
    })
    .catch(() => {
      //取消
    });
};

//关闭弹出层
const colosClick = function () {
  getAllRoleTreeMsg();
  isVisibles.value = false;
};

//关闭菜单权限抽屉
const colosMenuDrawerClick = function () {
  isMenuDrawerVisibles.value = false;
};

//关闭菜单权限抽屉
const colosButtonDrawerClick = function () {
  isButtonDrawerVisibles.value = false;
};
//关闭绑定用户抽屉
const colosBindUserDrawerClick = function () {
  isBindUserVisibles.value = false;
};

//禁止点页面的滑块
const switchClick = function () {
  return new Promise((_, reject) => {
    return reject(new Error("Error"));
  });
};

const ref1 = ref<ButtonInstance>();
const ref2 = ref<ButtonInstance>();
const ref3 = ref<ButtonInstance>();
const ref4 = ref<ButtonInstance>();
</script>
<style scoped>
.rowStyle {
  border: 1px solid #00152914;
  box-shadow: 0 1px 4px #00152914;
  margin-bottom: 3px;
}
.colStyle {
  height: 50px;
  display: flex;
  justify-content: left;
  align-items: center;
  padding-left: 5px;
}

/* 定义关键帧动画 */
@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

/* 应用动画到元素 */
.blink-text {
  animation: blink 2s infinite; /* 持续时间1秒，无限次播放 */
}
</style>